package com.phkj.qdh.ui.fragment

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.hjq.toast.ToastUtils
import com.phkj.qdh.base.BaseVM
import com.phkj.qdh.bean.HomeNoticeBean
import com.phkj.qdh.net.PageList
import com.phkj.qdh.net.code
import com.phkj.qdh.net.msg
import com.phkj.qdh.repository.HomeRepository
import com.phkj.qdh.utils.requestIO
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest

class HomeVM(val home: HomeRepository) : BaseVM() {

    private val _homeNotificationList = MutableSharedFlow<ArrayList<HomeNoticeBean>>()
    val homeNotificationList get() = _homeNotificationList

    private val _state = MutableSharedFlow<Int>()
    val state get() = _state
    fun getHomeNotificationList(map: HashMap<String, Any?>) {

        requestIO {
            home.getHomeNotificationList(map).catch { cause ->
                ToastUtils.show(cause.msg)
                stop(cause.code)
            }.collectLatest {
                _homeNotificationList.emit(it.data)
                stop(0)
            }
        }
    }

    private suspend fun stop(i: Int) {
        _state.emit(i)
    }
}


fun getHomeProvider() = HomeVMProvider(HomeRepository)

class HomeVMProvider(val home: HomeRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return HomeVM(home) as T
    }
}